//index.js
//获取应用实例
var app = getApp()
var queryAddressUrl = "addressApi/queryAddress";
var orderVerifyUrl = "userOrderApi/orderVerify";
var orderVerifyUpdateUrl = "userOrderApi/orderVerifyUpdate";
var orderCreateUrl = "userOrderApi/orderCreate";
var batchNo;
var token;
var shr;
var tel;
var shopList = [];
var updateType = 1;
var totalPrice;
var adress = {
  addressP: "",
  addressC: "",
  addressQ: "",
  addressDetail: "",
}
Page({
  data: {
    goodsList: [],
    isNeedLogistics: 0, // 是否需要物流信息
    allGoodsPrice: 0,
    yunPrice: 0,
    allGoodsAndYunPrice: 0,
    goodsJsonStr: "",
    orderType: "", //订单类型，购物车下单或立即支付下单，默认是购物车，
    hasNoCoupons: true,
    coupons: [],
    youhuijine: 0, //优惠券金额
    curCoupon: null, // 当前选择使用的优惠券
    isUpdate: updateType,
    leaveMsg:''
  },

  onLoad: function (e) {
    wx.showLoading();
    // console.log(e)
    var that = this;
    //显示收货地址标识
    that.setData({
      isNeedLogistics: 1,
      orderType: e.orderType
    });

    var dataList = [];
    wx.request({
      url: app.globalData.requestUrl + queryAddressUrl,
      header: {
        'content-type': 'application/json'
      },
      method: 'POST',
      data: {//这里写你要请求的参数
        memberId: app.globalData.userId
      },
      success: (res) => {
        console.log(res)

        var index;
        for (var i = 0; i < res.data.list.length; ++i) {
          if (res.data.list[i].defaultAddress == "C129001") {
            dataList = res.data.list[i];
          }
        }

        that.setData({
          curAddressData: dataList
        });
        adress.addressP = dataList.provinceId;
        adress.addressC = dataList.cityId;
        adress.addressQ = dataList.countryId;
        adress.addressDetail = dataList.addressDetail;
        shr = dataList.person;
        tel = dataList.tel;
        var goodsList = JSON.parse(e.goodsList);
        console.log(goodsList)
        wx.request({

          url: app.globalData.requestUrl + orderVerifyUrl,
          header: {
            'content-type': 'application/json'
          },
          method: 'POST',
          data: {//这里写你要请求的参数
            userId: app.globalData.userId,
            addressP: adress.addressP,
            addressC: adress.addressC,
            addressQ: adress.addressQ,
            addressDetail: adress.addressDetail,
            orderMethod: 2,
            goodsList: goodsList,
            locateCity: getApp().getCity, //上海市  //app.globalData.locatCity
            deviceType: 'C142001',
            signType: 'MD5',
            orderChannelType: "C212004",
            orderChannelValue: "",
            sign: "000000005cc84c33015cd3e721250070"
          },

          success: (res) => {
            wx.hideLoading();
            console.log(res)
            var goodsnum = res.data.data.shopList[0].goodsList.length;
            totalPrice = res.data.data.shopList[0].totalPrice;
            shopList = res.data.data.shopList;
            console.log(shopList)
            batchNo = res.data.data.batchNo;
            token = res.data.data.token;
            that.setData({
              goodsList: res.data.data.shopList[0].goodsList,
              yunPrice: res.data.data.shopList[0].totalFreightFee,
              goodsnum: goodsnum,
              totalPrice: totalPrice
            });

          }

        })

      }
    })

  },
  onShow: function () {
    var that = this;
    var isUpdate = that.data.isUpdate;

    if (isUpdate == 2) {
      var pages = getCurrentPages();
      var currPage = pages[pages.length - 1];   //当前页面
      that.setData({
        'curAddressData.provinceName': currPage.data.adress.addressP,
        'curAddressData.cityName': currPage.data.adress.addressC,
        'curAddressData.countryName': currPage.data.adress.addressQ,
        'curAddressData.addressDetail': currPage.data.adress.addressDetail,
        'curAddressData.person': currPage.data.person,
        'curAddressData.tel': currPage.data.tel,
      });


      // 调用更新确认订单接口
      wx.request({
        url: app.globalData.requestUrl + orderVerifyUpdateUrl,
        header: {
          'content-type': 'application/json'
        },
        method: 'POST',
        data: {//这里写你要请求的参数
          userId: app.globalData.userId,
          addressP: adress.addressP,
          addressC: adress.addressC,
          addressQ: adress.addressQ,
          addressDetail: adress.addressDetail,
          couponsId: "",
          deviceType: 'C142001',
          signType: 'MD5',
          batchNo: batchNo,
          token: token
        },

        success: (res) => {
          console.log(res)
          var goodsnum = res.data.data.shopList[0].goodsList.length;
          totalPrice = res.data.data.shopList[0].totalPrice;
          batchNo = res.data.data.batchNo;
          token = res.data.data.token;
          that.setData({
            goodsList: res.data.data.shopList[0].goodsList,
            yunPrice: res.data.data.shopList[0].totalFreightFee,
            goodsnum: goodsnum,
            totalPrice: totalPrice
          });
        }

      })

    }
  },
  getDistrictId: function (obj, aaa) {
    if (!obj) {
      return "";
    }
    if (!aaa) {
      return "";
    }
    return aaa;
  },
  leavemsgInput:function(e){
    this.setData({
      leaveMsg: e.detail.value
    })
  },
  createOrder: function (e) {
    var that = this;
    console.log(shopList);
    var goodsList = shopList[0].goodsList;
    console.log(goodsList);
    var list = [
      {
        shopId:"",
        remark:""
      }
    ];

    for(var i=0;i<shopList.length;i++){
      list.shopId = shopList[i].shopId;
      list.remark = that.data.leaveMsg;
    }
    console.log(list);
    wx.request({
      url: app.globalData.requestUrl + orderCreateUrl,
      header: {
        'content-type': 'application/json'
      },
      method: 'POST',
      data: {//这里写你要请求的参数
        userId: app.globalData.userId,
        deviceType: 'C142001',
        batchNo: batchNo,
        token: token,
        shr: shr,
        tel: tel,
        addressP: adress.addressP,
        addressC: adress.addressC,
        addressQ: adress.addressQ,
        addressDetail: adress.addressDetail,
        locateCity: getApp().getCity,
        shopList: list,
        sellShipperId:"",
        signType: 'MD5',
        sign: '000000005cc84c33015cd3e721250070'
      },

      success: (res) => {
        console.log(res);
        console.log(batchNo);
        if (res.data.status == 1) {
          wx.navigateTo({
            url: "/pages/confirm-pay/confirm-pay?money=" + totalPrice + "&batchNo=" + batchNo
          });
        }else{
          wx.showToast({
            title: '请求下单失败',
            duration: 2000
          })
        }
      }
    })
  },

  // processYunfei: function () {
  //   var that = this;
  //   var goodsList = this.data.goodsList;
  //   var goodsJsonStr = "[";
  //   var isNeedLogistics = 0;
  //   var allGoodsPrice = 0;

  //   for (let i = 0; i < goodsList.length; i++) {
  //     let carShopBean = goodsList[i];
  //     if (carShopBean.logistics) {
  //       isNeedLogistics = 1;
  //     }
  //     allGoodsPrice += carShopBean.price * carShopBean.number;

  //     var goodsJsonStrTmp = '';
  //     if (i > 0) {
  //       goodsJsonStrTmp = ",";
  //     }


  //     let inviter_id = 0;
  //     let inviter_id_storge = wx.getStorageSync('inviter_id_' + carShopBean.goodsId);
  //     if (inviter_id_storge) {
  //       inviter_id = inviter_id_storge;
  //     }


  //     goodsJsonStrTmp += '{"goodsId":' + carShopBean.goodsId + ',"number":' + carShopBean.number + ',"propertyChildIds":"' + carShopBean.propertyChildIds + '","logisticsType":0, "inviter_id":' + inviter_id + '}';
  //     goodsJsonStr += goodsJsonStrTmp;


  //   }
  //   goodsJsonStr += "]";
  //   //console.log(goodsJsonStr);
  //   that.setData({
  //     isNeedLogistics: isNeedLogistics,
  //     goodsJsonStr: goodsJsonStr
  //   });
  //   // that.createOrder();
  // },
  addAddress: function () {
    wx.navigateTo({
      url: "/pages/address-add/address-add"
    })
  },
  selectAddress: function () {
    wx.navigateTo({
      url: "/pages/select-address/select-address?whereGo=" + 1
    })
  },

  bindChangeCoupon: function (e) {
    const selIndex = e.detail.value[0] - 1;
    if (selIndex == -1) {
      this.setData({
        youhuijine: 0,
        curCoupon: null
      });
      return;
    }
    this.setData({
      youhuijine: this.data.coupons[selIndex].money,
      curCoupon: this.data.coupons[selIndex]
    });
  }
})
